from course.model import Classtable
from user.model import User
from app import scheduler
import access
import json
import requests
import datetime
import logging


def notify(num, school):
    if school == 'scauzj':
        logging.debug('num: %s  school: %s, ready to push' % (num, school))
        n_str = ['第一节', '第二节', '第三节', '第四节', '第五节', '第六节'][int(num) - 1]
        objs = []
        with open('admin/classtable.json', 'r', encoding='utf-8')as f:
            objs = json.loads(f.read())['tables']
            f.close()
        d = []
        for i in range(len(objs)):
            if 'scauzj' == objs[i]['value']:
                d = objs[i]['date'].split('-')
                break

        startday = datetime.datetime(int(d[0]), int(d[1]), int(d[2]))
        nowday = datetime.datetime.now()
        daycount = (nowday - startday).days
        week = daycount // 7 + 1  # 计算今天是第几周
        print('week: %d' % week)

        with scheduler.app.app_context():
            tables = Classtable.query.filter_by(week=week).all()  # 取出所有本周的数据

        for table in tables:  # 遍历每一个人的本周
            with scheduler.app.app_context():
                user = User.query.filter_by(id=table.userid).first()  # 取得用户
            if user.reminder == 1 and user.school == 'scauzj':  # 开启推送
                content = json.loads(table.data)['classtable'][datetime.datetime.now().weekday()]  # 获得今天的数据
                for c in content:  # 每一节课查找
                    if c['num'] == n_str:  # 如果当前第几节和课程命中，则推送
                        push(user, c['courseName'], c['time'], c['className'])
    elif school == 'ynnubs':
        logging.debug('num: %s  school: %s, ready to push' % (num, school))
        n_str = ['第一节', '第二节', '第三节', '第四节', '第五节', '第六节'][int(num) - 1]
        objs = []
        with open('admin/classtable.json', 'r', encoding='utf-8')as f:
            objs = json.loads(f.read())['tables']
            f.close()
        d = []
        for i in range(len(objs)):
            if 'ynnubs' == objs[i]['value']:
                d = objs[i]['date'].split('-')
                break

        startday = datetime.datetime(int(d[0]), int(d[1]), int(d[2]))
        nowday = datetime.datetime.now()
        daycount = (nowday - startday).days
        week = daycount // 7 + 1  # 计算今天是第几周
        print('week: %d' % week)

        with scheduler.app.app_context():
            tables = Classtable.query.filter_by(week=week).all()  # 取出所有本周的数据

        for table in tables:  # 遍历每一个人的本周
            with scheduler.app.app_context():
                user = User.query.filter_by(id=table.userid).first()  # 取得用户
            if user.reminder == 1 and user.school == 'ynnubs':  # 开启推送
                content = json.loads(table.data)['classtable'][datetime.datetime.now().weekday()]  # 获得今天的数据
                for c in content:  # 每一节课查找
                    if c['num'] == n_str:  # 如果当前第几节和课程命中，则推送
                        push(user, c['courseName'], c['time'], c['className'])


def push(user: User, name, t, room):
    token = access.getToken()
    data = {
        "touser": user.openid2,
        'template_id': '52U-MJJrQQga5VncwyinI_0jzXYFtczbQgdS55YgxEw',
        'data': {
            "first": {
                "value": "课程提醒",
                "color": "#173177"
            },
            "keyword1": {
                "value": name,
                "color": "#173177"
            },
            "keyword2": {
                "value": t,
                "color": "#173177"
            },
            "keyword3": {
                "value": room,
                "color": "#173177"
            },
            "remark": {
                "value": "还有20分钟上课，请提前做好准备！",
                "color": "#173177"
            }
        }
    }

    template = json.dumps(data)
    res2 = requests.post(
        'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' + token, data=template)
    logging.debug('user: %d   name: %s   time: %s   room: %s   res: %s' % (user.id, name, t, room, res2.text))
